﻿<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>

<% 
   ModelMetadata meta = ViewData.ModelMetadata;
   string currentAction = ViewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.ToLower();
   bool isAjax = meta.AdditionalValues.ContainsKey("IsAjax") ? Convert.ToBoolean(meta.AdditionalValues["IsAjax"]) : false;
   string onChangeActions = meta.AdditionalValues.ContainsKey("OnChangeActions") ? meta.AdditionalValues["OnChangeActions"].ToString().ToLower() : "create";
   
   string masterTable = meta.AdditionalValues["MasterTable"].ToString();
   string masterController = meta.AdditionalValues.ContainsKey("MasterController") ? meta.AdditionalValues["MasterController"].ToString() : masterTable;
   string onChangeFunctionName = !onChangeActions.Contains(currentAction) ? "" : (meta.AdditionalValues.ContainsKey("OnChangeFunctionName") ? meta.AdditionalValues["onChangeFunctionName"].ToString() : "");
   string propertyName = meta.AdditionalValues.ContainsKey("PropertyName") ? meta.AdditionalValues["PropertyName"].ToString() : meta.PropertyName;
   string displayName = meta.DisplayName;
   bool isRequired = meta.AdditionalValues.ContainsKey("Required") ? Convert.ToBoolean(meta.AdditionalValues["Required"]) : meta.IsRequired;
   
   string methodName = meta.AdditionalValues.ContainsKey("MethodName") ? meta.AdditionalValues["MethodName"].ToString() : "";
   string notSetName = meta.AdditionalValues.ContainsKey("NotSetName") ? meta.AdditionalValues["NotSetName"].ToString() : "";
   //!fn$GetConsumableUnitListItems!p$4
   string ajaxRequestData = string.Format("PartialView$ForiegnFieldData!Model${0}!MasterTable${1}!PropertyName${2}!IsRequired${3}!ocf${4}!nsn${5}!fn${6}!p$", Model, masterTable, propertyName, isRequired, onChangeFunctionName, notSetName, methodName);
       
   ViewDataDictionary VDD = new ViewDataDictionary();
   VDD["MasterTable"] = masterTable;
   VDD["PropertyName"] = propertyName;
   VDD["IsRequired"] = isRequired;
   VDD["ocf"] = onChangeFunctionName;
   VDD["nsn"] = notSetName;
   
   VDD["IsAjax"] = isAjax;

   string iframeSrc = string.Format("http://{0}/{1}/Create?iframe=true", Request.Url.Authority, masterController);
   string iframeInitSrc = string.Format("http://{0}/{1}/RenderEmptyView", Request.Url.Authority, "Home");
%>

<div id="partial<%:propertyName %>">
<% Html.RenderPartial("~/Views/Shared/EditorTemplates/ForiegnFieldData.ascx", (object)Model, VDD);%>
</div>
<a id="feedback-open-button<%:propertyName %>" href="#">Create New <%:displayName%></a><img id="loading<%:propertyName %>" src="../../../Content/Default/loading.gif" alt="Updating ..." style="display: none;float:right;margin-left:5px;" />


     <%-- <% 
            ModelMetadata meta = ViewData.ModelMetadata;

            List<KeyValuePair<string, string>> items = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetListItemsByTableName(meta.AdditionalValues["MasterTable"].ToString());
            if (!meta.IsRequired)
                items.Insert(0, new KeyValuePair<string, string>("", "[Not Set]"));

            int maxLengthIndex =0;
            for (int i = 0; i < items.Count; i++)
            {
                if (items[maxLengthIndex].Value.Length < items[i].Value.Length)
                {
                    maxLengthIndex = i;
                }
            }
       %>
      
       <%: Html.Telerik().ComboBox()
                                      .Name(meta.PropertyName)
                                      .AutoFill(true)
                                      .SelectedIndex(0)
                                      .BindTo(new SelectList(items, "Key", "Value", Model))
                                      .HtmlAttributes(new { style = "float:left;"})
                                      .HighlightFirstMatch(true)
                                      .ClientEvents(events => events.OnChange("SetInputValue"))
                                      .OpenOnFocus(true)
                                      %>

     <div class="t-item" id="invisdiv<%:meta.PropertyName %>" style="background-color:Black;color:White;visibility:hidden;display:inline-block;">
        <%:items.Count>0? items[maxLengthIndex].Value:"" %>
    </div>

    <script type="text/javascript">
        SetInputValue();
        $(document).ready(function () {
            var comboWidth<%:meta.PropertyName %> = $("#invisdiv<%:meta.PropertyName %>").width() +40;
            $("#<%:meta.PropertyName %>").prev().parent().width(comboWidth<%:meta.PropertyName %>);
        });
    
    function SetInputValue()
        {
        if($("#<%:meta.PropertyName %>-input").val()=="[Not Set]"){
    $("#<%:meta.PropertyName %>").val("");
    }
        }
    </script>
--%>
   
     <% Html.Telerik().Window()
           .Name("Window" + propertyName)
           .ClientEvents(
              events =>
                events.OnClose("onClose" + propertyName).OnLoad((AMSManager.InsideIframe ? "onLoad" : "onLoad2") + propertyName)
                )
           .Title("Create New " + displayName)
           .Draggable(true)
           .Resizable()
           .Scrollable(false)
           .Modal(true)
           .Buttons(b => b.Maximize().Close())
           //.LoadContentFrom("Create","Countries")
           .LoadContentFrom(iframeInitSrc)
           .Width(900)
           .Height(500)
           .Visible(false)
           .Render();
    %>
    
 <% Html.Telerik().ScriptRegistrar()
           .OnDocumentReady(() =>
           {%>
               // open the initially hidden window when the button is clicked
               $('#feedback-open-button<%:propertyName %>')
                    .click(function(e) {
                        e.preventDefault();
                         var window = $("#Window<%:propertyName %>").data("tWindow");
                         var iframe = $("#Window<%:propertyName %> iframe")[0];
                         iframe.src = "<%:iframeSrc%>";
                        window.center().open();
                    });
               // add button hovers
               $('.t-button').live('mouseenter', $.telerik.buttonHover)
                             .live('mouseleave', $.telerik.buttonLeave);

                            <%-- if('<%:isAjax%>'=='True')
                             {
               RenderForiegnFieldData<%:propertyName %>()
               }--%>
           <%}); %>

                <a id="closeWindow<%:propertyName %>" href="#" onclick="closeWindow<%:propertyName %>();"  style="visibility:hidden">close</a>
        
             <script type="text/javascript">
             
             function RenderForiegnFieldData<%:propertyName %>() {
                     $('#loading<%:propertyName %>').show();
                     $('#partial<%:propertyName %>').html('');
                     $('#partial<%:propertyName %>').load('/Home/RenderForiegnPartialView/<%:ajaxRequestData %>'+((typeof <%:propertyName %>AjaxParameter == 'undefined')?'':<%:propertyName %>AjaxParameter), function (html) {
                         $('#partial<%:propertyName %>')[0].value = html;
                         $('#loading<%:propertyName %>').hide();
                                          });
                 }

                 function onLoad<%:propertyName %>(e) {
                     //                    $.ajaxSetup({ cache: false }); 
                     //alert('Window loaded');
                     maximizeWindow<%:propertyName %>();
                 }
                 function onLoad2<%:propertyName %>(e) {
                    
                 }
                 function onClose<%:propertyName %>(e) {
                    RenderForiegnFieldData<%:propertyName %>()
                 }
                 function onOpen<%:propertyName %>(e) {
//                     alert('OnOpen');
                 }
                 function onActivate<%:propertyName %>(e) {
//                     alert('OnActivate');
                 }
                 function onRefresh<%:propertyName %>(e) {
//                     alert('OnRefresh');
                 }


                 function openWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.open();
                 }

                 function closeWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.close();
                 }

                 function refreshWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     alert("refresh");
                     window.refresh();
                 }

                 function maximizeWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.maximize();
                 }

                 function restoreWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.restore();
                 }

                 function centerWindow<%:propertyName %>() {
                     var window = $("#Window<%:propertyName %>").data("tWindow");
                     window.center();
                 }
        </script>
